import { memo, forwardRef, useImperativeHandle, useRef, useEffect, useState } from 'react'
import LdDialog from '../../../../../components/LdDialog'
import { Input, Form, Button, message } from 'antd'
import bus from '../../../../../utils/eventBus'
import './index.scss'
const AddDivision = forwardRef((props: any, ref: any) => {
    const { row, success, close } = props
    const formRef = useRef<any>(null)
    const [loading, setLoading] = useState<boolean>(false)
    const handleSave = () => {
        formRef.current.validateFields().then((res: any) => {
            if (row?.type === 2) {
                window.chromePro.modDepartment(JSON.stringify({ ...row, newName: res.name }));
            } else {
                window.chromePro.addDepartment(
                    JSON.stringify({ name:res.name, parentId: row ? row.id : "",newName: res.name })
                );
            }
        }).catch(() => { })
    }
    const addDepartmentFinished = (data: any) => {
        if (data.code === 200) {
            message.success("新增成功");
            success && success()
            close && close()
        } else {
            setLoading(false)
            message.error(data.msg);
        }
    }
    const modDepartmentFinished = (data: any) => {
        if (data.code === 200) {
            success && success()
            message.success("修改成功");
            close && close()
        } else {
            setLoading(false)
            message.error(data.msg);
        }
    }
    useEffect(() => {
        if (row) {
            formRef.current.setFieldsValue({
                name: row.name
            })
        }
        bus.addListener("addDepartmentFinished", addDepartmentFinished);
        bus.addListener("modDepartmentFinished", modDepartmentFinished);
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener("addDepartmentFinished", addDepartmentFinished);
            bus.removeListener("modDepartmentFinished", modDepartmentFinished);
        }
    }, [])
    return (
        <LdDialog handleClose={close} title={row ? '编辑机构' : '新增机构'}>
            <Form ref={formRef} labelCol={{ span: 5 }} style={{ width: '380px', margin: '0 auto' }}>
                <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入机构名称' }]}>
                    <Input placeholder='请输入机构名称' />
                </Form.Item>
            </Form>
            <div className="footer">
                <Button loading={loading} type="primary" onClick={handleSave} className="footer-btn">保存</Button>
            </div>
        </LdDialog >
    )
})
export default memo(AddDivision)